package com.raycloud.erp.omll.provider.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.omall.open.sdk.domain.LogisticsCompany;
import com.raycloud.erp.omll.provider.constant.OmallLogisticsCompaniesAlias;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 物流公司列表
 *
 * @author 枫伦
 * @DESCRIPTION
 * @create 2021/1/6 11:09 上午
 */
@Service
@Slf4j
public class LogisticsNoService {
//    public static void main(String[] args) throws IOException {
//        ClassPathResource classPathResource = new ClassPathResource("/omall/companies.json");
//        InputStream inputStream = classPathResource.getInputStream();
//
//
//        System.out.println(readJsonFile(inputStream));
//    }

    Map<String, LogisticsCompany> companies = new HashMap<String, LogisticsCompany>();


    @PostConstruct
    public void load() {
        try {
            ClassPathResource classPathResource = new ClassPathResource("/omall/companies.json");
            InputStream inputStream = classPathResource.getInputStream();
            String jsonString = readJsonFile(inputStream);
            List<LogisticsCompany> companyList = JSONArray.parseArray(jsonString, LogisticsCompany.class);
            loadMap(companyList);
        } catch (Exception e) {
            log.error("加载洋葱的物流公司出错:" + e.getMessage(), e);
        }
    }

    private void loadMap(List<LogisticsCompany> list) {
        for (LogisticsCompany company : list) {
            companies.put(company.getName(), company);
        }
    }

    public Map<String, LogisticsCompany> getCompaniesMap() {
        return this.companies;
    }

    /**
     * 根据物流公司名称进行查询
     *
     * @param name
     * @return
     */
    public LogisticsCompany queryCompany(String name) {
        String alias = OmallLogisticsCompaniesAlias.getAlias(name);
        return companies.get(null != alias ? alias : name);
    }

    public String readJsonFile(InputStream inputStream) {
        BufferedReader reader = null;
        String readJson = "";
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                readJson += tempString;
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
        return readJson;
    }

}
